import { Avatar, Badge, Dropdown, Menu, Modal } from "@arco-design/web-react"
import { Conversation, MessageType, TextMessage } from "../../../domain/im/entity";
import { getTimeStringAutoShort2 } from "../../../domain/time";
import { LeoAvatar } from "../../../components/leo_Avatar";
import { useDispatch, useSelector } from "react-redux";

import http from "../../../http";
import { deleteConversation, fetchConversationList } from "../../../store/features/conversation";
import { deleteMessage } from "../../../store/features/message";



// user 当前登录用户 // message 消息
export const createGroupMessageText = (user: any, message: any) => {
    const dataContent = JSON.parse(message.dataContent);
    const p1 = user.userId == dataContent.creator.userId ? "你  " : `${dataContent.creator.nickName}  `;
    const p2 = '创建了群，并邀请了'
    const names = dataContent.invitations.map((item: any) => {
        return item.userId == user.userId ? "你" : item.nickName;
    })
    return `${p1}${p2}${names.join("、")}加入该群`;
}


export const invitedUserJoin = (user: any, message: any) => {
    const dataContent = JSON.parse(message.dataContent);
    const p1 = user.userId == dataContent.invitation.userId ? "你  " : `${dataContent.invitation.nickName}  `;
    const p2 = '邀请了 '
    const names = dataContent.invitations.map((item: any) => {
        return item.userId == user.userId ? "你" : item.nickName;
    })
    return `${p1}${p2}${names.join("、")}加入该群`;
}

export const removeUsersGroup = (user: any, message: any) => {
    const dataContent = JSON.parse(message.dataContent);
    const p1 = user.userId == dataContent.Operator.userId ? "你  " : `${dataContent.Operator.nickName}  `;
    const p2 = '移出了 '
    const names = dataContent.removes.map((item: any) => {
        return item.userId == user.userId ? "你" : item.nickName;
    })
    return `${p1}${p2}${names.join("、")}`;
}


export const updateNameGroup = (user: any, message: any) => {
    const dataContent = JSON.parse(message.dataContent);
    const p1 = user.userId == dataContent.Operator.userId ? "你  " : `${dataContent.Operator.nickName}  `;
    const p2 = `把 ${dataContent.originalName} 修改为 ${dataContent.currentName} `;
    return `${p1}${p2}`

}


export const SessionItem: React.FC<{ index: number, conversation: Conversation, select: Boolean, onClick: (index: number) => void }> = ({ index, conversation, select, onClick }) => {


    const { user } = useSelector((state: any) => state.user.value);


    const { list, current } = useSelector((state: any) => state.conversation.value);


    const getLastMessageText = (lastMessage: any) => {

        const message = JSON.parse(lastMessage);
        if (message.typeu == MessageType.TxtMsg) {
            const dataContent = JSON.parse(message.dataContent);
            return dataContent.content;
        } else if (message.typeu == MessageType.ImgMsg) {
            return "[图片]";
        } else if (message.typeu == MessageType.FileMsg) {
            return "[文件]";
        } else if (message.typeu == MessageType.SightMsg) {
            return "[视频]";
        } else if (message.typeu == MessageType.VideoOffer) {
            return "[视频通话]";
        } else if (message.typeu == MessageType.VerifiedBy) {
            return "我通过了你的朋友验证请求，现在我们可以开始聊天了";
        } else if (message.typeu == MessageType.createGroup) {
            return createGroupMessageText(user, message);
        } else if (message.typeu == MessageType.invitationGroup) {
            return invitedUserJoin(user, message)
        } else if (message.typeu == MessageType.removeUserGroup) {
            return removeUsersGroup(user, message)
        } else if (message.typeu == MessageType.updateNameGroup) {
            return updateNameGroup(user, message)
        } else if (message.typeu == MessageType.noticeGroup) {
            return "[群公告]"
        }
        else {
            console.log("---------");
            console.log(message);
            return "[未知]"
        }
    }

    const dispatch = useDispatch()



    return <>
        <div onClick={() => onClick(index)} className={`flex flex-row items-center cursor-pointer `} >

            <Dropdown
                trigger='contextMenu'
                position='bl'
                droplist={
                    <Menu>
                        <Menu.Item key='1' onClick={() => {
                            const fetchData = async () => {
                                const respone = await http.get(`/conversation/top?targetId=${conversation.targetId}`)
                                dispatch(fetchConversationList(list[current].targetId))
                            }

                            fetchData();

                        }}>{!conversation.top ? '置顶' : '取消置顶'}</Menu.Item>
                        <Menu.Item key='2' onClick={() => {
                            const fetchData = async () => {
                                const respone = await http.get(`/conversation/setDisturb?targetId=${conversation.targetId}`)
                                dispatch(fetchConversationList(conversation.targetId))
                            }
                            fetchData();
                        }}>{conversation.disturb ? "允许消息通知" : "消息免打扰"}</Menu.Item>
                        <Menu.Item key='3' onClick={() => {
                            Modal.confirm({
                                title: '确认要删除吗？',
                                content: '删除之后会清空消息记录，无法恢复！',
                                okButtonProps: {
                                    status: 'danger',
                                },
                                onOk: () => {
                                    const fetchData = async () => {
                                        const respone = await http.get(`/conversation/remove?targetId=${conversation.targetId}&clearMessages=true`)
                                        dispatch(deleteConversation({ targetId: conversation.targetId, currentTargetId: list[current].targetId }))
                                        dispatch(deleteMessage({ targetId: conversation.targetId }))
                                        dispatch(fetchConversationList())

                                        return true;
                                    }
                                    return fetchData();
                                },
                            });
                        }}>删除</Menu.Item>
                    </Menu>
                }
            >

                <div className={`flex-1 flex items-center rounded-[14px]  min-h-[70px]  my-1 mr-[8px] contacts ml-[8px] ${select ? 'bg-[#F4F9FD]' : ''}`}>
                    <div className="ml-2">
                        <Badge count={conversation.unreadCount}>
                            <LeoAvatar userPortrait={conversation.portrait} userName={conversation.userName} ></LeoAvatar>
                        </Badge>
                    </div>
                    <div className="mx-[14px] flex flex-col items-start flex-1">
                        <div className="flex w-full justify-between flex-row text-[16px]">
                            <div className="text-[16px] line-clamp-1  flex-1 text-left max-w-[100px]">{conversation.remark ? conversation.remark : conversation.userName}</div>
                            <div className="text-[14px] text-[#7D8592]">{getTimeStringAutoShort2(conversation.timestamp, true)}</div>
                        </div>
                        {
                            conversation.lastMessage &&
                            <div className="text-left mt-[3px] max-w-[200px] text-[14px] line-clamp-1 text-[#91929E]">
                                {getLastMessageText(conversation.lastMessage)}
                            </div>
                        }
                    </div>
                </div>
            </Dropdown>
            {select ? <div className="w-[4px] h-[60px] rounded-[2px] bg-[#3F8CFF]"></div> : <></>}
        </div>
    </>
}